import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAddressStore = defineStore('address', () => {
  const addresses = ref([
    {
      id: 1,
      name: '墨小枢',
      phone: '13800138000',
      province: '江西省',
      city: '上饶市',
      district: '信州区',
      detail: '信州区',
    }
  ])
  
  // 添加地址
  const addAddress = (address) => {
    // 如果是默认地址，取消其他默认
    if (address.isDefault) {
      addresses.value.forEach(item => {
        item.isDefault = false
      })
    }
    // 生成唯一ID
    address.id = Date.now()
    addresses.value.push(address)
    saveToStorage()
  }
  
  // 编辑地址
  const updateAddress = (address) => {
    const index = addresses.value.findIndex(item => item.id === address.id)
    if (index > -1) {
      // 如果设为默认，取消其他默认
      if (address.isDefault) {
        addresses.value.forEach(item => {
          item.isDefault = false
        })
      }
      addresses.value[index] = address
      saveToStorage()
    }
  }
  
  // 删除地址
  const deleteAddress = (id) => {
    const index = addresses.value.findIndex(item => item.id === id)
    if (index > -1) {
      addresses.value.splice(index, 1)
      saveToStorage()
    }
  }
  
  // 获取默认地址
  const getDefaultAddress = () => {
    return addresses.value.find(item => item.isDefault)
  }
  
  // 保存到本地存储
  const saveToStorage = () => {
    uni.setStorageSync('addresses', addresses.value)
  }
  
  // 从本地存储加载
  const loadFromStorage = () => {
    const stored = uni.getStorageSync('addresses')
    if (stored) {
      addresses.value = stored
    }
  }
  
  // 初始化时加载数据
  loadFromStorage()
  
  return {
    addresses,
    addAddress,
    updateAddress,
    deleteAddress,
    getDefaultAddress
  }
}) 
